package com.studyhub.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.studyhub.question.mapper.QuestionMapper;
import com.studyhub.question.model.dto.QuestionCreateDTO;
import com.studyhub.question.model.dto.QuestionQueryDTO;
import com.studyhub.question.model.entity.QueQuestionEntity;
import com.studyhub.question.model.vo.QuestionVO;
import com.studyhub.question.service.QuestionService;
import com.studyhub.web.utils.UserAuthUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问题服务实现类
 */
@Service
@RequiredArgsConstructor
public class QuestionServiceImpl implements QuestionService {
    
    private final QuestionMapper questionMapper;
    
    @Override
    @Transactional
    public Long createQuestion(QuestionCreateDTO createDTO) {
        // 获取当前登录用户ID
        Integer userId = UserAuthUtil.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 创建问题实体
        QueQuestionEntity question = new QueQuestionEntity();
        question.setUserId(userId);
        question.setQuestionType(createDTO.getQuestionType());
        question.setTitle(createDTO.getTitle());
        question.setContent(createDTO.getContent());
        question.setPublishTime(new Date());
        question.setLikeCount(0);
        question.setHotDegree(0);
        
        // 保存到数据库
        questionMapper.insert(question);
        
        return question.getQuestionId();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<QuestionVO> getQuestionList(QuestionQueryDTO queryDTO) {
        // 计算分页偏移量
        int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();
        
        // 查询问题列表
        List<QuestionVO> questions = questionMapper.selectQuestionList(
            queryDTO.getQuestionType(), 
            queryDTO.getKeyword(),
            offset, 
            queryDTO.getPageSize()
        );
        
        // 组装用户信息到VO中
        questions.forEach(this::buildQuestionVO);
        
        return questions;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getQuestionListWithPagination(QuestionQueryDTO queryDTO) {
        // 计算分页偏移量
        int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();
        
        // 查询问题列表
        List<QuestionVO> questionList = questionMapper.selectQuestionList(
            queryDTO.getQuestionType(), 
            queryDTO.getKeyword(),
            offset, 
            queryDTO.getPageSize()
        );
        
        // 组装用户信息到VO中
        questionList.forEach(this::buildQuestionVO);
        
        // 查询问题总数
        Integer total = questionMapper.selectQuestionCount(queryDTO.getQuestionType(), queryDTO.getKeyword());
        
        // 计算总页数
        Integer totalPages = (int) Math.ceil((double) total / queryDTO.getPageSize());
        
        // 返回分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", questionList);
        result.put("total", total);
        result.put("pageNum", queryDTO.getPageNum());
        result.put("pageSize", queryDTO.getPageSize());
        result.put("totalPages", totalPages);
        
        return result;
    }
    
    @Override
    public QuestionVO getQuestionDetail(Long questionId) {
        QuestionVO questionVO = questionMapper.selectQuestionDetail(questionId);
        if (questionVO == null) {
            throw new RuntimeException("问题不存在");
        }
        
        buildQuestionVO(questionVO);
        return questionVO;
    }
    
    @Override
    @Transactional
    public void deleteQuestion(Long questionId) {
        // 获取当前用户ID
        Integer userId = UserAuthUtil.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 查询问题
        QueQuestionEntity question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new RuntimeException("问题不存在");
        }
        
        // 检查是否为问题作者
        if (!question.getUserId().equals(userId)) {
            throw new RuntimeException("只有问题作者才能删除问题");
        }
        
        // 删除问题
        questionMapper.deleteById(questionId);
    }
    
    @Override
    @Transactional
    public void likeQuestion(Long questionId, boolean isLike) {
        // 获取当前用户ID
        Integer userId = UserAuthUtil.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 更新点赞数（这里简化处理，实际项目中需要防止重复点赞）
        int increment = isLike ? 1 : -1;
        questionMapper.updateLikeCount(questionId, increment);
        
        // 更新热度值（点赞增加热度）
        if (isLike) {
            questionMapper.updateHotDegree(questionId, 2);
        }
    }
    
    /**
     * 构建问题VO对象
     */
    private void buildQuestionVO(QuestionVO questionVO) {
        // 这里的用户信息已经在SQL中关联查询了
        // 如果需要更复杂的用户信息处理，可以在这里扩展
    }
}
